package cn.com.chengmandian.core.db.config;

import cn.com.chengmandian.core.db.properties.DbTenantProperties;
import cn.com.chengmandian.core.tenant.TenantUtil;
import cn.com.chengmandian.core.tenant.pojo.TenantInfo;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

@Configuration
@Slf4j
public class MybatisPlusConfig {
    @Autowired
    private DbTenantProperties dbTenantProperties;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 多租户支持
        if (dbTenantProperties.isEnable()) {
            log.info("start tenant mode!");
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
                @Override
                public Expression getTenantId() {
                    if (dbTenantProperties.getColumn().equals("agent_id")) {
                        return LocalMapUtil.getAgentInfo() != null ? new LongValue(LocalMapUtil.getAgentInfo().getId()) : null;
                    } else if (dbTenantProperties.getColumn().equals("company_id")) {
                        return LocalMapUtil.getCompanyInfo() != null ? new LongValue(LocalMapUtil.getCompanyInfo().getId()) : null;
                    } else {
                        TenantInfo tenantInfo = TenantUtil.get();
                        return tenantInfo != null ? new LongValue(tenantInfo.getId()) : null;
                    }
                }

                @Override
                public String getTenantIdColumn() {
                    return dbTenantProperties.getColumn();
                }

                @Override
                public boolean ignoreTable(String tableName) {
                    return !CollectionUtils.isEmpty(dbTenantProperties.getIgnore()) && ArrayUtil.contains(dbTenantProperties.getIgnore().toArray(), tableName);
                }
            }));
        }

        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
